#include "CImageLoader.h"

CImageLoader::CImageLoader() : loadedImage(0)
{
    #ifdef DEBUG
    this->_logger = CLogger::Instance();
    #endif
}

CImageLoader::~CImageLoader()
{
    /* free surface and texture */
    if (loadedImage != 0)
    {
        SDL_FreeSurface(loadedImage);
        #ifdef DEBUG
        this->_logger->log(LOG_LEVEL_NOTICE,"SDL Surface deleted");
        this->_logger->Release();
        #endif
    }
}

//http://gpwiki.org/index.php/SDL:Tutorials:Using_SDL_with_OpenGL
/**
  * CImageLoader::loadImageFile
  *
  * @param filename
  */
SDL_Surface* CImageLoader::loadImageFile(std::string filename)
{
    loadedImage = IMG_Load(filename.c_str());
    /*filename check*/
    if (loadedImage == 0)
    {
        #ifdef DEBUG
        this->_logger->log(LOG_LEVEL_WARN,"CImageLoader::loadImageFile : Image %s not found",filename.c_str());
        #endif
        return NULL;
    }
    /*check that image size is power of 2*/
   /* if ((loadedImage->w & (loadedImage->w -1)) != 0)
    {
        std::cerr << "warning: width is not power of 2 (" << loadedImage->w << ")" << std::endl;
        return NULL;
    }
    if ((loadedImage->h & (loadedImage->h -1)) != 0)
    {
        std::cerr << "warning: height is not power of 2 (" << loadedImage->h << ")" << std::endl;
        return NULL;
    }*/
    if (loadedImage->format->BitsPerPixel < 24)
    {
        #ifdef DEBUG
        this->_logger->log(LOG_LEVEL_WARN,"CImageLoader::loadImageFile : image not truecolor");
        #endif
        return NULL;
    }

        #ifdef DEBUG
        this->_logger->log(LOG_LEVEL_NOTICE,"CImageLoader::loadImageFile : image %s loaded",filename.c_str());
        #endif

        SDL_DisplayFormat(loadedImage);
    return loadedImage;
}
